package com.leadingsoft.web.core.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.leadingsoft.common.constant.Constant;
import com.leadingsoft.common.utils.MD5Utils;
import com.leadingsoft.core.dto.ResultType;
import com.leadingsoft.core.pojo.UserInfo;
import com.leadingsoft.web.core.service.CoreService;

@Controller
@RequestMapping(value = "/w/core/", produces = "text/plain;charset=UTF-8")
public class CoreController {
	@Autowired
	private CoreService coreService;

	@RequestMapping("authorizations/myAuthorizedMenus")
	@ResponseBody
	public String myAuthorizedMenus() {
		return "";
	}
	@RequestMapping("checkLogin")
	@ResponseBody
	public String checkLogin(HttpServletRequest request) {
		// 验证session
		UserInfo userInfo = (UserInfo) request.getSession().getAttribute(Constant.SESSION_ID);
		if (null != userInfo) {
			return ResultType.success();
		} else {
			return ResultType.fail("");
		}
	}
	@RequestMapping("login")
	@ResponseBody
	public String login(UserInfo userInfo, HttpServletRequest request) {
		UserInfo u = coreService.login(userInfo);
		if (null != u) {
			request.getSession().setAttribute(Constant.SESSION_ID, u);
			// token account nickname
			// account
			String account = u.getLoginAccount();
			// token
			String token = MD5Utils.Encrypt(account, true);
			// nickname
			String nickname = u.getNickname();
			Map<String, String> resultMap = new HashMap<String, String>();
			resultMap.put("account", account);
			resultMap.put("token", token);
			resultMap.put("nickname", nickname);
			// 保存token到数据库
			coreService.saveToken(u.getuId(), account, token);
			return ResultType.success(resultMap);
		}
		return ResultType.fail("账号或密码错误");
	}
	@RequestMapping("logout")
	@ResponseBody
	public String logout(HttpServletRequest request) {
		// 清除session
		request.getSession().removeAttribute(Constant.SESSION_ID);
		// 使token失效
		String token = request.getHeader("TOKEN");
		coreService.logout(token);
		return ResultType.success();
	}
}
